package k8s

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"kubeimooc/global"
	pod_req "kubeimooc/model/pod/request"
	"kubeimooc/response"
	"net/http"
)

type PodApi struct {
}

/*
*
获取pod的列表
*/
func (p *PodApi) GetPodList(c *gin.Context) {
	ctx := context.TODO()
	//查询所有的pod
	list, err := global.KubeConfigSet.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
	if err != nil {
		fmt.Print(err.Error())
	}
	for _, item := range list.Items {
		fmt.Println(item.Namespace, item.Name)
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "getPodList ok",
	})
}

/*
*
vue后台返回pod列表或者详情
*/
func (p PodApi) GetPodListOrDetail(c *gin.Context) {
	namespace := c.Param("namespace") //
	name := c.Query("name")
	keyword := c.Query("keyword")
	nodeName := c.Query("nodeName")
	if name != "" {
		//获取pod详情
		podReq, err := podService.GetPodDetail(namespace, name)
		if err != nil {
			response.FailWithMessage(c, err.Error())
			return
		}
		response.SuccessWithDetail(c, "获取pod详情成功", podReq)
	} else {
		//获取pod列表
		err, items := podService.GetPodList(namespace, keyword, nodeName)
		if err != nil {
			response.FailWithMessage(c, err.Error())
			return
		}
		response.SuccessWithDetail(c, "获取pod列表成功", items)
	}
}

/*
*
创建或者更新pod
*/
func (p *PodApi) CreateOrUpdatePod(c *gin.Context) {
	var podReq pod_req.Pod
	if err := c.ShouldBind(&podReq); err != nil {
		response.FailWithMessage(c, "参数解析失败,detail:"+err.Error())
		return
	}
	//检验必填项
	if err := podValidate.Validate(&podReq); err != nil {
		response.FailWithMessage(c, "参数校验失败,detail:"+err.Error())
		return
	}
	//创建或者更新pod
	if msg, err := podService.CreateOrUpdatePod(podReq); err != nil {
		response.FailWithMessage(c, msg)
	} else {
		response.SuccessWithMessage(c, msg)
	}
}

/*
*
直接创建pod
*/
func (p *PodApi) CreatePod(c *gin.Context) {
	var podReq pod_req.Pod
	if err := c.ShouldBind(&podReq); err != nil {
		response.FailWithMessage(c, "参数解析失败,detail:"+err.Error())
		return
	}
	//检验必填项
	if err := podValidate.Validate(&podReq); err != nil {
		response.FailWithMessage(c, "参数校验失败,detail:"+err.Error())
		return
	}
	if msg, err := podService.CreatePod(podReq); err != nil {
		response.FailWithMessage(c, msg)
	} else {
		response.SuccessWithMessage(c, msg)
	}
}

/*
*
删除pod
*/
func (p *PodApi) DeletePod(c *gin.Context) {
	namespace := c.Param("namespace")
	name := c.Param("name")
	err := podService.DeletePod(namespace, name)
	if err != nil {
		response.FailWithMessage(c, "删除pod失败,detail:"+err.Error())
	} else {
		response.Success(c)
	}
}
